package web.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import web.common.Result;
import web.exception.CaptchaException;
import web.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败 账号密码错误
 * 401 =
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        Result res = null;
        System.out.println(authException);
        if (authException instanceof CaptchaException) {
            String  exstring=authException.getMessage();
            switch (exstring) {
                case "501":
                    res = Result.DiyCode(501, "签名不能为空");
                return;
                case "502":
                    res = Result.DiyCode(502, "超时");
                    return;
                case "503":
                    res = Result.DiyCode(503, "重复请求");
                    return;
                case "504":
                    res = Result.DiyCode(504, "签名错误");
                    return;
                default:
                    res = Result.DiyCode(444, "验证码错误");
                    return;
            }

        } else {
            res = Result.DiyCode(401, "认证失败");
        }

        String s = JSON.toJSONString(res);
        WebUtils.renderString(response, s);
    }
}
